package com.java.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson2.JSON;
import com.java.entity.RaceAccount;
import com.java.service.AccountService;
import com.java.util.MyTools;
import com.java.util.resp.BaseRespone;
import com.java.util.resp.TableRespone;
import com.java.util.servlet.ServletUtil;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired private AccountService accountService;

    @Autowired RestTemplate restTemplate;
    
    @Value("${weixin.appid}") String appid;
    
    @Value("${weixin.secret}") String secret;
	
	@PostMapping("/authWx")
	public BaseRespone authWx(String code, String encryptedData, String iv) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
				+appid+"&secret="
				+secret+"&js_code=" 
				+ code + "&grant_type=authorization_code";
		String forObject = restTemplate.getForObject(url, String.class);
        try {
            // 将json转为map
            @SuppressWarnings("rawtypes")
			Map map = JSON.parseObject(forObject, Map.class);
            if (map.containsKey("openid")) {
                String openid = map.get("openid").toString();
                String session_key = map.get("session_key").toString();
                Map info = MyTools.wxDecrypt(encryptedData, session_key, iv);
                if(null != info) {
                	RaceAccount account = accountService.getAccountByOpenId(openid);
                	if(null == account) {
                		account = new RaceAccount();
                		account.setAccountOpenId(openid);
                		account.setAccountName(MyTools.getStringRandom(6));
                		account.setAccountNick(info.get("nickName").toString());
                		account.setAccountLogo(info.get("avatarUrl").toString());
                		return new BaseRespone(1, "暂未绑定账号", account);
                	}
            		return new BaseRespone(0, "登录成功", account);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
		return BaseRespone.error("授权失败");
	}
 
	
	@PostMapping("/authBind")
	public BaseRespone authBind(@RequestBody RaceAccount account) {
		// String number, String openId, String nick, String logo
		// String number, String openId, String nick, String logo, Integer type
		return accountService.saveAuth(account.getAccountNumber(), account.getAccountOpenId(), 
				account.getAccountNick(), account.getAccountLogo());
	}
	
	@PostMapping("/info")
	public BaseRespone info() {
		RaceAccount student = accountService.getAccount(ServletUtil.getUserId(null));
		return BaseRespone.success(student);
	}
	
	@PostMapping("/saveInfo")
	public BaseRespone saveInfo(@RequestBody RaceAccount account) {
		return accountService.update(account);
	}
	
	@PostMapping("/getAccount")
	public RaceAccount getAccount(
			@RequestParam(required = true) String accountId) {
		return accountService.getAccount(accountId);
	}

	@PostMapping("/getAccounts")
	public TableRespone getAccounts(
			@RequestParam(required = false, defaultValue = "") Integer type,
			@RequestParam(required = false, defaultValue = "0") int page,
			@RequestParam(required = false, defaultValue = "0") int size) {
		return accountService.getAccountList(type, page, size);
	}
	
	@PostMapping("/createAccount")
	public BaseRespone createAccount(@RequestBody RaceAccount account) {
		return accountService.createAccount(account);
	}
	
}
